package com.system.insurance.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.system.common.result.Result;
import com.system.insurance.entity.*;
import com.system.insurance.service.*;
import com.system.insurance.utils.AuthContextUtil;
import com.system.insurance.utils.UniqueValueUtils;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 报价单对询价用户回复 前端控制器
 * </p>
 *
 * @author WS
 * @since 2024-05-28
 */
@RestController
@RequestMapping("/insurance/quotation-form")
public class QuotationFormController {


    protected static final Logger log = LoggerFactory.getLogger(WechatPay2Validator.class);

    @Autowired
    private QuotationFormService quotationFormService;


    @Autowired
    private AppletUserService appletUserService;


    @Autowired
    private NumberOfTimesService numberOfTimesService;

    @Autowired
    private OfferRecordService offerRecordService;


    @Autowired
    private FormFillingService formFillingService;


    @ApiOperation(value = "询价方：查看自己所有报价单")
    @GetMapping("/quotationFormBjd/{smallId}")
    public Result<List<QuotationForm>> quotationFormBjd(@PathVariable Integer smallId){

        String s = AuthContextUtil.get();
        AppletUser byId = appletUserService.getById(Integer.valueOf(s));

        LambdaQueryWrapper<QuotationForm> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(QuotationForm::getSmallid,smallId).eq(QuotationForm::getXjuserid,Integer.valueOf(s));
        List<QuotationForm> list = quotationFormService.list(wrapper);

        for (int i = 0; i < list.size(); i++) {
            if (byId.getNum()>=list.size()){

                QuotationForm formFilling = list.get(i);
                formFilling.setNum(1);
                quotationFormService.save(formFilling);
            }else {

                QuotationForm formFilling = list.get(i);
//
//                List<NumberOfTimes> list1 = numberOfTimesService.list();
//                for (int i1 = 0; i1 < list1.size(); i1++) {
//                    BigDecimal price = list1.get(0).getPrice();
//                    formFilling.setQuotationOfPrice(price);
//                }
                formFilling.setNum(2);
                quotationFormService.save(formFilling);
            }

        }
        return Result.ok(list);
    }


    // TODO  需要改进，是不能传两个对象的，因为其中对象传完，就会关闭对象流，请求不到第二个对象。
    @ApiOperation(value = "报价方: 添加报价方保险内容")
    @PostMapping("/saveQuotationForm")
    public Result<QuotationForm> saveQuotationForm(@RequestBody QuotationForm quotationForm){

        quotationForm.setCreateTime(LocalDateTime.now());

        String s = AuthContextUtil.get();
        quotationForm.setXjuserid(quotationForm.getXjuserid());
        quotationForm.setBjuserid(Integer.valueOf(s));
        quotationForm.setSmallid(quotationForm.getSmallid());
        quotationForm.setXjname(quotationForm.getXjname());
        quotationForm.setXjcompany(quotationForm.getXjcompany());
        quotationForm.setStart(0);

        boolean save = quotationFormService.save(quotationForm);

        LambdaQueryWrapper<FormFilling> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FormFilling::getSmallid,quotationForm.getSmallid()).eq(FormFilling::getXjUserId,quotationForm.getXjuserid());
        FormFilling one = formFillingService.getOne(wrapper);
        one.setNumber(one.getNumber()+1);

        formFillingService.updateById(one);
        if (save){
            return Result.ok(quotationForm).message("添加成功");
        }
        return Result.fail(quotationForm).message("添加失败");
    }




//    @ApiOperation(value = "询价方：查看自己单个报价单")
//    @PostMapping("/QuotationFormBjdById")
//    public Result quotationFormBjdById(@RequestBody QuotationForm quotationForm,HttpServletRequest request, HttpServletResponse response){
//
//        String s = AuthContextUtil.get();
//        if (quotationForm.getNum()==1) {
//            LambdaQueryWrapper<QuotationForm> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(QuotationForm::getId, quotationForm.getId());
//            QuotationForm list = quotationFormService.getOne(wrapper);
//            return Result.ok(list);
//
//        }else if (quotationForm.getNum()==2){
////TODO 支付功能
//            List<NumberOfTimes> list = numberOfTimesService.list();
//            for (int i = 0; i < list.size(); i++) {
//
//                BigDecimal price = list.get(0).getPrice();
//                OfferRecord offerRecord = new OfferRecord();
//                offerRecord.setAppletUserId(Integer.valueOf(s));
//                offerRecord.setOrderNumber(UniqueValueUtils.createByDateTime());
//                offerRecord.setBjdid(quotationForm.getId());
//                offerRecord.setPrice(price);
//
//                boolean isSuccess = offerRecordService.save(offerRecord);
//
//                if (isSuccess) {
//                // 根据刚生成的订单号，查询订单信息获取订单id
////            QueryWrapper<EvaluationRecord> queryWrapper = new QueryWrapper<>();
////            queryWrapper.eq("order_id", reward1.getOrderId());
//                LambdaQueryWrapper<OfferRecord> queryWrapper = new LambdaQueryWrapper<>();
//                queryWrapper.eq(OfferRecord::getOrderNumber, offerRecord.getOrderNumber());
//
//                    OfferRecord orderDetail = offerRecordService.getOne(queryWrapper);
//                Integer id = orderDetail.getBjdid();
//                log.info("CarteOrdersPay" + id);
//                Object ordersPay = offerRecordService.CarteOrdersPay(request, response,orderDetail);
//                if (ordersPay != null) {
////                    return Result.ok(ordersPay);
////          LambdaQueryWrapper<QuotationForm> wrapper = new LambdaQueryWrapper<>();
////            wrapper.eq(QuotationForm::getId, quotationForm.getId());
////            QuotationForm list1 = quotationFormService.getOne(wrapper);
//
//            return Result.ok(ordersPay);
//                } else {
//                    return Result.fail("支付失败！");
//                }
//            } else {
//                return Result.fail("订单创建失败！");
//            }
//        }
//
//    }
//
//                    return Result.fail().message("没有数据！");
//}








//    /**
//     * 微信通知回调地址
//     *
//     * @param request
//     * @param response
//     * @return
//     */
//    @PostMapping("/wxBuy")
//    public String wxBuy(HttpServletRequest request, HttpServletResponse response) {
//        System.out.println("===========微信回调============");
//        Object o = offerRecordService.wxBuy(request, response);
//        if (o != null) {
//            return "success";
//        }
//        return "failed";
//
//    }
//
//
//    /**
//     * 提供给前端查询支付订单状态的接口
//     *
//     * @param orderId
//     * @return
//     */
//    @GetMapping("/queryOderStatus")
//    public Result queryOderStatus(@RequestParam String orderId) {
//        OfferRecord orderDetail = offerRecordService.getOrders(orderId);
//        if (orderDetail != null) {
//            return Result.ok(orderDetail);
//        }
//        return Result.fail("sorry,没有查询到该订单");
//    }
//
//    /**
//     * 查询订单的一个接口回调
//     *# orderNo
//     * @param orderNumber
//     *
//     * @return
//     * @throws Exception
//     */
//    @GetMapping("/query")
//    public Result queryOrder(@RequestParam String orderNumber) throws Exception {
//        Object queryOrder = offerRecordService.queryOderStatus(orderNumber);
//        if (queryOrder != null) {
//            return Result.ok(queryOrder);
//        }
//        return Result.fail("failed");
//    }

}

